
#include "GLtexture.h"

STLvector<GLtexture*> GLtexture::m_texList;

GLtexture::GLtexture()
{
	m_id = 0;
	m_slot = -1;
}

GLtexture::~GLtexture()
{
}

bool GLtexture::LoadFile( const TCHAR* filename)
{
	TCHAR ss[MAX_PATH];
	GetCurrentDirectory(MAX_PATH,ss); 
	ILstring s = const_cast<TCHAR*>  ( filename );
	
	GLuint id = ilutGLLoadImage( s );
	m_id = id;

	m_file_path = filename;

	return true;
}

void GLtexture::Destroy()
{	
	if( m_id > 0){
		glDeleteTextures( 1,&m_id );
		m_id = 0;
	}

	m_slot = -1;
}

void GLtexture::DeleteTexture( GLtexture* texture)
{
	int index = texture->GetSlotIndex();
	if( index >= 0){
		texture->Destroy();
		delete GLtexture::m_texList[index];
		GLtexture::m_texList[index] = NULL;
	}
}

void GLtexture::ClearTextureList()
{
	int nTextures = m_texList.Count();
	for( int i = 0;i<nTextures;i++ ){
		if( GLtexture::m_texList[i] ){
			GLtexture::DeleteTexture( GLtexture::m_texList[i] );
		}
	}
	
	GLtexture::m_texList.clear();
}

GLtexture* GLtexture::LoadTexture( const TCHAR* filename )
{
	GLtexture* texture = FindTexture( filename );

	if(!texture){
		texture = new GLtexture;
		texture->LoadFile( filename );
		TCHAR name[MAX_PATH];
		_splitpath(filename,NULL,NULL,name,NULL);
		texture->m_name = name;
		int slot = GLtexture::FindSlot();
		GLtexture::m_texList[slot] = texture;
		texture->m_slot = slot;
	}
	
	texture->AddRef();	

	return texture;
}

GLtexture* GLtexture::FindTexture( const TCHAR* filename )
{
	int nSlot = m_texList.Count();
	for( int i = 0;i<nSlot;i++ ){
		if( m_texList[i] ){
			if( m_texList[i]->m_file_path == filename ){
				return m_texList[i];
			}
		}
	}

	return NULL;
}

int GLtexture::FindSlot(){
	int index = -1;
	int nSlot = m_texList.Count();
	for( int i = 0;i<nSlot;i++ ){
		if( m_texList[i] ){
			index = i;
			break;
		}
	}

	if( index ==- 1){
		index = m_texList.Count();
		m_texList.push_back( NULL );
	}

	return index;
}